package com.example.demo.config.rabbitMq;

import com.alibaba.fastjson.JSON;
import com.example.demo.RabbitMQTest.entity.QueueMessage;
import com.example.demo.RabbitMQTest.util.MQConstant;
import com.example.demo.common.service.IMessageService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by 75949 on 2019/12/27.
 */

//延迟消息接收处理消费者
@Component
@RabbitListener(queues = MQConstant.DEFAULT_REPEAT_TRADE_QUEUE_NAME)
@Slf4j
public class ReceiverDelayMessage {

    @Autowired
    private IMessageService messageService;

    @RabbitHandler
    private void process(@Payload String content, Message msg, Channel channel) throws IOException {
        try {
            //此时，才把消息发送到指定队列，而实现延迟功能
            QueueMessage message = JSON.parseObject(content, QueueMessage.class);
            message.setType(1);
            messageService.send(message);
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            if (msg.getMessageProperties().getRedelivered()) {
                log.error("消息已重复处理失败,拒绝再次接收");
                // 拒绝消息，requeue=false 表示不再重新入队，如果配置了死信队列则进入死信队列
                channel.basicReject(msg.getMessageProperties().getDeliveryTag(), false);
            } else {
                log.error("消息即将再次返回队列处理");
                // requeue为是否重新回到队列，true重新入队
                channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
